package com.lyeducation.util;

import com.alibaba.fastjson.JSON;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.*;

/**
 * @ClassName Md5Utils
 * @Description
 * @Author Sky1in3
 * @Date 2019/1/11 14:24
 * @Version 1.0
 */
public class Md5Utils {

    private static final String SIGN_KEY = "sign";

    /**
     * 获取数据 md5 摘要并返回 Base64 编码后的字符串
     *
     * @param data
     * @return
     */
    public static String md5Base64(String data) {
        return Base64.getEncoder().encodeToString(DigestUtils.md5(data));
    }

    /**
     * 将 javaBean 进行json序列号后返回包含签名 (sign) 的 json 字符串
     *
     * @param javaBean
     * @return
     */
    public static String setSignWithJsonObj(Object javaBean, String salt) {
        Map<String, String> mapObj = JSON.parseObject(JSON.toJSONString(javaBean), HashMap.class);
        ArrayList<String> keys = new ArrayList<>(10);
        mapObj.forEach((key, value) -> keys.add(key));
        Collections.sort(keys);
        boolean isFirst = true;
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < keys.size(); i++) {
            String key = keys.get(i);
            String value = mapObj.get(key);
            if (SIGN_KEY.equals(key)) {
                continue;
            }
            if (org.apache.commons.lang3.StringUtils.isNotBlank(value)) {
                if (isFirst) {
                    sb.append(keys.get(i)).append("=").append(value);
                    isFirst = false;
                } else {
                    sb.append("&").append(keys.get(i)).append("=").append(value);
                }
            }
        }
        if (org.apache.commons.lang3.StringUtils.isNotBlank(salt)) {
            sb.append("&salt=").append(salt);
        }
        System.out.println(sb.toString());
        String sign = md5Base64(sb.toString());
        mapObj.put(SIGN_KEY, sign);

        return JSON.toJSONString(mapObj);
    }

    /**
     * 判断签名是否一致
     *
     * @param signature
     * @param data
     * @return
     */
    public boolean md5CheckBase64(String signature, String data) {
        if (StringUtils.isAnyBlank(signature, data)) {
            return false;
        }
        return md5Base64(data).equals(signature);
    }

}

